﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;

using ConstructionBidOnline.DAL;
using ConstructionBidOnline.DAL.dsEmailCategoryTableAdapters;
using ConstructionBidOnline.Common;

namespace ConstructionBidOnline.Biz
{
    /// <summary>
    /// Email Category Business Object
    /// </summary>

    public class EmailCategory : BOBase
    {


        #region Construction / Disposal

        /// <summary>
        /// Default constructor.
        /// </summary>
        protected EmailCategory() { }

        #endregion

        #region Public Properties

        #region Instance Properties

        /// <summary>
        /// PKID of the EmailCategory.
        /// </summary>
        public int EmailCategoryID
        {
            get { return _emailcategoryID; }
            set
            {
                if (_emailcategoryID != value)
                {
                    if (OnPropertyChanging("EmailCategoryID", _emailcategoryID, value))
                    {
                        int oldValue = _emailcategoryID;
                        _emailcategoryID = value;

                        OnPropertyChanged("EmailCategoryID", oldValue, value);
                    }
                }
            }
        }  private int _emailcategoryID = -1;

        /// <summary>
        /// Email Category Value.
        /// </summary>
        public string EmailCategoryName
        {
            get { return _Emailcategoryname; }
            set
            {
                if (_Emailcategoryname != value)
                {
                    if (OnPropertyChanging("EmailCategoryName", _Emailcategoryname, value))
                    {
                        string oldValue = _Emailcategoryname;
                        _Emailcategoryname = value;
                        OnPropertyChanged("EmailCategoryName", oldValue, value);
                    }
                }
            }
        }  private string _Emailcategoryname = null;


        /// <summary>
        /// Email Category Description.
        /// </summary>
        public string EmailCategoryDescription
        {
            get { return _Emailcategorydescription; }
            set
            {
                if (_Emailcategorydescription != value)
                {
                    if (OnPropertyChanging("EmailCategoryDescription", _Emailcategorydescription, value))
                    {
                        string oldValue = _Emailcategorydescription;
                        _Emailcategorydescription = value;
                        OnPropertyChanged("EmailCategoryDescription", oldValue, value);
                    }
                }
            }
        }  private string _Emailcategorydescription = null;


        /// <summary>
        /// Date/time at which the EmailCategory was created.
        /// </summary>
        public DateTime? AddedDate
        {
            get { return _addedDate; }
            set
            {
                if (_addedDate != value)
                {
                    if (OnPropertyChanging("AddedDate", _addedDate, value))
                    {
                        DateTime? oldValue = _addedDate;
                        _addedDate = value;
                        OnPropertyChanged("AddedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _addedDate = null;

        /// <summary>
        /// Date/time at which the EmailCategory was updated.
        /// </summary>
        public DateTime? UpdatedDate
        {
            get { return _updatedDate; }
            set
            {
                if (_updatedDate != value)
                {
                    if (OnPropertyChanging("UpdatedDate", _updatedDate, value))
                    {
                        DateTime? oldValue = _updatedDate;
                        _updatedDate = value;
                        OnPropertyChanged("UpdatedDate", oldValue, value);
                    }
                }
            }
        }  private DateTime? _updatedDate = null;


        /// <summary>
        /// True iff the Admin has made this EmailCategory Active (i.e. to be used in the application).
        /// </summary>
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (_isActive != value)
                {
                    if (OnPropertyChanging("IsActive", _isActive, value))
                    {
                        bool oldValue = _isActive;
                        _isActive = value;
                        OnPropertyChanged("IsActive", oldValue, value);
                    }
                }
            }
        }  private bool _isActive = false;

        #endregion

        #endregion

        #region Public Methods

        #region CreateNew

        /// <summary>
        /// Creates a new, empty EmailCategory object.
        /// </summary>
        public static EmailCategory CreateNew()
        {
            EmailCategory obj = new EmailCategory();

            // Switch state to Added prior to initializing property values.
            obj.ObjState = ObjectState.Added;

            obj.AddedDate = DateTime.Now;
            obj.UpdatedDate = DateTime.Now;
            obj.IsActive = true;
            return (obj);
        }


        [MethodImpl(MethodImplOptions.Synchronized)]
        public static EmailCategory CreateNew(EmailCategoryCollection collection)
        {
            EmailCategory obj = CreateNew();

            // Get next/unique ID for the new object.
            int minVal = 0;
            foreach (EmailCategory Emailcategory in collection)
            {
                if (Emailcategory.EmailCategoryID < minVal)
                    minVal = Emailcategory.EmailCategoryID;
            }
            obj.EmailCategoryID = --minVal;
            collection.Add(obj);

            return (obj);
        }

        #endregion

        #region GetAllEmailCategories

        /// <summary>
        /// Returns a collection of all EmailCategory.
        /// </summary>
        public static EmailCategoryCollection GetAllEmailCategories()
        {
            EmailCategoryTableAdapter adapter = new EmailCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();

            dsEmailCategory.EmailCategoryDataTable tbl = adapter.GetData(null);

            EmailCategoryCollection list = new EmailCategoryCollection();

            if (tbl.Rows.Count > 0)
            {
                foreach (dsEmailCategory.EmailCategoryRow row in tbl.Rows)
                {
                    EmailCategory Emailcategory = new EmailCategory();
                    RelationalToObject(Emailcategory, row);
                    list.Add(Emailcategory);
                }
            }

            return (list);
        }

        #endregion

        #region GetEmailCategoryByID

        /// <summary>
        /// Returns an EmailCategory object for the specified 'EmailCategoryID' or null if no EmailCategory with the specified parameter(s) exists.
        /// </summary>
        public static EmailCategory GetEmailCategoryByID(int Emailcategoryid)
        {
            EmailCategoryTableAdapter adapter = new EmailCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsEmailCategory.EmailCategoryDataTable tbl = adapter.GetData(Emailcategoryid);

            if (tbl.Rows.Count == 1)
            {
                EmailCategory dc = new EmailCategory();
                RelationalToObject(dc, tbl.Rows[0]);
                return (dc);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'Email' returned more than one record.");

            return (null);
        }

        #endregion

        #region GetEmailCategoryByEmailCategoryName

        /// <summary>
        /// Returns an EmailCategory object for the specified 'EmailCategoryName' or null if no EmailCategory with the specified parameter(s) exists.
        /// </summary>
        public static EmailCategory GetEmailCategoryByEmailCategoryName(string emailcategoryname)
        {
            EmailCategoryTableAdapter adapter = new EmailCategoryTableAdapter();
            adapter.Connection = AppSettings.GetDbConn();
            dsEmailCategory.EmailCategoryDataTable tbl = adapter.GetDataByEmailCategoryName(emailcategoryname);

            if (tbl.Rows.Count == 1)
            {
                EmailCategory emailcategoryObj = new EmailCategory();
                RelationalToObject(emailcategoryObj, tbl.Rows[0]);
                return (emailcategoryObj);
            }
            else if (tbl.Rows.Count > 1)
                throw new ApplicationException("Database integrity error: Specified 'emailcategory' returned more than one emailcategory.");

            return (null);
        }

        #endregion


        #region Update

        /// <summary>
        /// Updates the specified EmailCategory.
        /// </summary>
        public static void Update(EmailCategory obj)
        {
            bool updateEmailCategory = false;

            // Do not update invalid objects.
            if (!obj.Validate())
            {
                StringBuilder sb = new StringBuilder(2048);
                sb.Append("The object being updated has one or more invalid properties; the Update() operation for this object has been cancelled.\nError(s):");
                foreach (ValidationError err in obj.Errors)
                    sb.Append("\n* " + err.Element + ": " + err.Message);

                throw new InvalidObjectException(sb.ToString());
            }
            else
            {
                updateEmailCategory = (obj.ObjState != ObjectState.Unchanged);

                if (!updateEmailCategory)
                    return;
            }

            ObjectState originalObjectState = obj.ObjState;

            dsEmailCategory.EmailCategoryDataTable tbl = null;
            if (updateEmailCategory)
            {
                EmailCategoryTableAdapter adapter = new EmailCategoryTableAdapter();
                adapter.Connection = AppSettings.GetDbConn();


                tbl = new dsEmailCategory.EmailCategoryDataTable();
                dsEmailCategory.EmailCategoryRow row = tbl.NewEmailCategoryRow();
                ObjectToRelational(obj, tbl, row);

                adapter.Update(tbl);

                if (originalObjectState == ObjectState.Deleted)
                    obj = null;
                else RelationalToObject(obj, tbl.Rows[0]);
            }
        }

        #endregion

        #region Validate

        /// <summary>
        /// Validates the object based on its properties at the time of the call; updates the Errors property.
        /// </summary>
        public override bool Validate()
        {
            Errors.Clear();

            if (ObjState == ObjectState.Unchanged)
            {
                // By definition, unchanged objects are valid.
                return (true);
            }
            else if (ObjState == ObjectState.Uninitialized)
            {
                Errors.Add(new ValidationError("object", "Object is uninitialized.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else if ((ObjState == ObjectState.Deleted) && (EmailCategoryID <= 0))
            {
                // Deleted items must have 'real' (i.e. non-negative, non-zero) key(s) to be valid.
                Errors.Add(new ValidationError("EmailCategoryID", "Deleted object has an invalid PKID.", ValidationError.Severity.Error));

                // No need to proceed past this error.
                return (false);
            }
            else  // ObjState == Added | Modified
            {

                // UserName is required.
                if ((EmailCategoryName == null) || (EmailCategoryName.Trim().Length == 0))
                {
                    Errors.Add(new ValidationError("EmailCategoryName", "EmailCategory is required.", ValidationError.Severity.Error));
                }
                else if (ObjState == ObjectState.Added)
                {

                }

            }

            return (Errors.Count == 0);
        }

        #endregion

        #region ToString

        /// <summary>
        /// User-friendly string represetation of this object.
        /// </summary>
        public override string ToString()
        {
            return (String.Format("EmailCategory: DCID={0}, EmailCategoryName={1}, {2}", EmailCategoryID, EmailCategoryName, EmailCategoryDescription));
        }

        #endregion

        #endregion

        #region Privates


        #endregion

    }

    /// <summary>
    /// Collection of 0 or more Email objects.
    /// </summary>

    public class EmailCategoryCollection : List<EmailCategory>
    {
        #region Types

        public class UserComparer : IComparer<EmailCategory>
        {
            public int Compare(EmailCategory dc1, EmailCategory dc2)
            {
                return (String.Compare(dc1.EmailCategoryName, dc2.EmailCategoryName));
            }
        }

        #endregion

        #region Public Methods

        #region FindByEmailCategoryID

        public EmailCategory FindByEmailCategoryID(int EmailcategoryID)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].EmailCategoryID == EmailcategoryID)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #region FindByEmailCategory

        /// <summary>
        /// Case insensitve compare.
        /// </summary>
        public EmailCategory FindByEmailCategory(string Emailcategoryname)
        {
            for (int ndx = 0; ndx < this.Count; ndx++)
                if (this[ndx].EmailCategoryName == Emailcategoryname)
                    return (this[ndx]);

            return (null);
        }

        #endregion

        #endregion

    }
}
